package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.common.RequirePermission;
import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.domain.query.QueryObject;
import cn.wolfcode.rbac.domain.vo.PageResult;
import cn.wolfcode.rbac.domain.vo.R;
import cn.wolfcode.rbac.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/department")
@CrossOrigin(allowCredentials = "true")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping("/list")
    @RequirePermission({"部门分页列表","department:list"})
    @PreAuthorize("hasAnyAuthority('department:list')")
    public R list(QueryObject qo) {
        PageResult<Department> pageResult;
        try {
            pageResult = departmentService.queryForList(qo);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok("查询成功",pageResult);
    }
    @GetMapping("/listAll")
    @RequirePermission({"部门列表","department:listAll"})
    @PreAuthorize("hasAnyAuthority('department:listAll')")
    public R listAll() {
        List<Department> departments = departmentService.selectAll();
        return R.ok("查询成功",departments);
    }
    @DeleteMapping("/delete/{id}")
    @RequirePermission({"部门删除","department:delete"})
    @PreAuthorize("hasAnyAuthority('department:delete')")
    public R delete(@PathVariable Long id) {
        try {
            departmentService.deleteById(id);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok("删除成功");
    }

    @GetMapping("/info/{id}")
    @RequirePermission({"部门信息","department:info"})
    @PreAuthorize("hasAnyAuthority('department:info')")
    public R info(@PathVariable Long id) {
        Department department;
        try {
            department = departmentService.selectById(id);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok("查询成功",department);
    }

    @PostMapping("/saveOrUpdate")
    @RequirePermission({"部门保存或更新","department:saveOrUpdate"})
    @PreAuthorize("hasAnyAuthority('department:saveOrUpdate')")
    public R saveOrUpdate(@RequestBody Department department) {
        try {
            departmentService.saveOrUpdate(department);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok("添加或修改成功");
    }

}
